package user

import (
	"errors"
	"github.com/gogf/gf/crypto/gmd5"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
	"websshop/app/model/ws_manage"
	"websshop/app/model/ws_user"
	user "websshop/app/module/user"
)

const (
	ADMIN_USER_SESSION_KEY  = "admin_user_info"
	USER_SESSION_KEY        = "user_info"
)

func RedirectUrl(r *ghttp.Response,url string)  {
	r.ResponseWriter.Header().Set("Location",url)
	r.ResponseWriter.WriteHeader(301)
}

func CreateAdminUser(data *user.CreateAdminUserArgs) error {
	var entity *ws_manage.Entity

	if err := gconv.Struct(data,&entity); err != nil {
		return err
	}

	entity.Ctime = gconv.Uint64(gtime.Now().Timestamp())
	entity.Utime = entity.Ctime
	if _,err := ws_manage.Save(entity); err != nil {
		return err
	}
	return nil
}



func IsLogin(session *ghttp.Session,userType string) bool {
	if userType == "Admin" {
		return session.Contains(ADMIN_USER_SESSION_KEY)
	}else {
		return session.Contains(USER_SESSION_KEY)
	}
}

func AdminLogin(data *user.LoginUserArgs,session *ghttp.Session) error {
	one,err := ws_manage.FindOne("username=?",data.Username)
	if err != nil {
		return err
	}
	if one == nil {
		return errors.New("用户不存在！")
	}
	if one.Password != gmd5.MustEncryptString(gmd5.MustEncryptString(data.Password) + gconv.String(one.Ctime)) {
		return errors.New("密码不正确！")
	}
	return session.Set(ADMIN_USER_SESSION_KEY,one)
}

func Login(data *user.LoginUserArgs,session *ghttp.Session) error  {
		one,err := ws_user.FindOne("username=?",data.Username)
		if err != nil {
			return err
		}
		if one == nil {
			return errors.New("用户不存在！")
		}
		if one.Password != gmd5.MustEncryptString(gmd5.MustEncryptString(data.Password) + gconv.String(one.Ctime)) {
			return errors.New("密码不正确！")
		}
		return session.Set(USER_SESSION_KEY,one)
}

func Logout(session *ghttp.Session,userType string) error  {
	if userType == "Admin" {
		return session.Remove(ADMIN_USER_SESSION_KEY)
	}else {
		return session.Remove(USER_SESSION_KEY)
	}
}

func GetUserInfo(session ghttp.Session) (u *ws_user.Entity) {
	_ = session.GetStruct(USER_SESSION_KEY,&u)
	return
}
func GetAdminUserInfo(session ghttp.Session) (u *ws_manage.Entity) {
	_ = session.GetStruct(ADMIN_USER_SESSION_KEY,&u)
	return
}





